package com.google.project.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.server.entity.Project;
import com.google.project.server.entity.DailyReportDetail;
import com.google.project.server.entity.ProjectStaff;
import com.google.project.server.entity.ProjectTask;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DailyReportDetailDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.project.shared.TaskConstrainDTO;


/**
 * the FriendsService communicates Friend data via RPC between client and
 * server.
 */
@SuppressWarnings("serial")
public class ProjTaskServiceImpl extends RemoteServiceServlet implements
		ProjTaskService {

	
	
	class DataY
	{
		public Double yValue;
		DataY()
		{
			yValue=0d;
		}
		DataY(Double value)
		{
			yValue=value;
		}
	}
	
	
	List<DataY> getDataOfSub(ProjectTaskDTO data , List<Long> Datax,List<ProjectTaskDTO> listTask)
	{
		List<DataY> result = new ArrayList<DataY>();
		//neu la task cha
		if(data.getSubTasks()!=null&&!data.getSubTasks().equals(""))
		{
			//neu co task con duyet task de tim task con
			for(ProjectTaskDTO task: listTask)
			{
				
				if(CommonFuntion.checkContain(data.getSubTasks(),task.getTaskId()+"")&&task.getStatus()!=3&&task.getStatus()!=0)
				{
					//lay ve list ket qua task con
					List<DataY> dataOfSub = getDataOfSub( task , Datax, listTask);
					//neu list ket qua cua task cha chua co du lieu 
					if(result.size()==0)
					{
						//duyet list ket qua task con va ad vao result
						for(DataY dataOfDay : dataOfSub)
						{
						
							Double workOfParent = data.getAmountOfWork()*(dataOfDay.yValue/task.getAmountOfWork())*task.getWeight()/100;
							DataY dataY = new DataY(workOfParent);
							
							result.add(dataY);
						}
					}
					else
					{

						//duyet list ket qua task con va cong don vao result
						int i =0;
						for(DataY dataOfDay : dataOfSub)
						{
						
							Double workOfParent = data.getAmountOfWork()*(dataOfDay.yValue/task.getAmountOfWork())*task.getWeight()/100;
							result.get(i).yValue = result.get(i).yValue + workOfParent;
							i++;
						}
						
					}
					
					
					
				}
			}
			
		}
		else
		{
			//lay ve du lieu cho task con 
			
			DailyReportDetailServiceImpl reportDetailServer = new DailyReportDetailServiceImpl();
			List<DailyReportDetailDTO> listReport = new ArrayList<DailyReportDetailDTO>();
			listReport = reportDetailServer.getDailyReportDetailByTask(data.getId());
			for (Long date : Datax) {
				Double work = getValueForDate(date,listReport);
				DataY workOfDay =new DataY(work);
				result.add(workOfDay);
			}
		}
		
		return result;
	}
	
	Double getValueForDate(Long date,List<DailyReportDetailDTO> data)
	{
		for(DailyReportDetailDTO report:data)
		{
			Date reportDate= new Date( report.getCreatedOnDate());
			
			String compareDate =CommonFuntion.convertToDate( new Date(date)	);
			
			String  reportDateNoTime= CommonFuntion.convertToDate(reportDate);
			if(compareDate.equals(reportDateNoTime)&&report.getStatus()!=3)
			{
				return report.getWorkToFinished();
			}
		}
		return 0d;
	}
	
	
	@Override
	public List<Double> getDataForHightChart(ProjectTaskDTO data , List<Long> Datax)
	{
		ProjectServiceImpl projectServer = new ProjectServiceImpl();
		List<DataY> result = new ArrayList<DataY>();
		List<ProjectTaskDTO> listTask = projectServer.getListTask(data.getProjectId());
		
		if(data.getSubTasks()!=null&&!data.getSubTasks().equals(""))
		{
			
			for(ProjectTaskDTO task: listTask)
			{
				if(CommonFuntion.checkContain(data.getSubTasks(),task.getTaskId()+"")&&task.getStatus()!=3&&task.getStatus()!=0)
				{
					List<DataY> dataOfSub = getDataOfSub( task , Datax, listTask);
					if(result.size()==0)
					{
						for(DataY dataOfDay : dataOfSub)
						{
						
							Double percentOfParent = (dataOfDay.yValue/task.getAmountOfWork())*task.getWeight();
							DataY dataY = new DataY(percentOfParent);
							
							result.add(dataY);
						}
					}
					else
					{
						int i =0;
						for(DataY dataOfDay : dataOfSub)
						{
						
							Double percentOfParent = (dataOfDay.yValue/task.getAmountOfWork())*task.getWeight();
							result.get(i).yValue = result.get(i).yValue + percentOfParent;
							i++;
						}
						
					}
					
					
					
				}
			}
			
		}
		else
		{
			//lay ve du lieu cho task con 
			
			DailyReportDetailServiceImpl reportDetailServer = new DailyReportDetailServiceImpl();
			List<DailyReportDetailDTO> listReport = new ArrayList<DailyReportDetailDTO>();
			listReport = reportDetailServer.getDailyReportDetailByTask(data.getId());
			for (Long date : Datax) {
				Double work = getValueForDate(date,listReport);
				DataY workOfDay =new DataY(work);
				result.add(workOfDay);
			}
		}
		
		List<Double> result2 = new ArrayList<Double>();
		for(DataY temp:result)
		{
			result2.add(CommonFuntion.fomatNumber(temp.yValue));
		}
		return result2;
	}
	
	@Override
	public void updateForFinish(ProjectTaskDTO data)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectStaffServiceImpl staffServer = new ProjectStaffServiceImpl();
		List<ProjectStaff> listStaff = staffServer.getStaffOfTask(data.getId());
		for(ProjectStaff staff:listStaff)
		{
			if(staff.getStatus()==0)
			{
				ProjectStaff temp = pm.getObjectById(ProjectStaff.class,staff.getId());
				pm.deletePersistent(temp);
			}else
			{
				ProjectStaff temp = pm.getObjectById(ProjectStaff.class,staff.getId());
				temp.setStatus(2);
			}
		}
		
		updateTask(data);
	}
@Override
public void updatePlan(ProjectTaskDTO data ,List<ProjectTaskDTO> list)
{
	PersistenceManager pm = PMF.get().getPersistenceManager();
	ProjectTask task = pm.getObjectById(ProjectTask.class,data.getId());
	Project project = pm.getObjectById(Project.class,data.getProjectId());
	//Long dateDiff = CommonFuntion.removeTime(new Date(data.getDueDate()))-CommonFuntion.removeTime(new Date(task.getDueDate()));
	task.setDueDate(CommonFuntion.removeTime(new Date(data.getDueDate())));
	String afterData="";
	if(task.getDependent()!=null&&!task.getDependent().equals(""))
	{
		afterData = task.getDependent().substring(task.getDependent().indexOf("|"));
		
		if(afterData.length()>1)
		{
			afterData=afterData.substring(1);
		}
		else
		{
			afterData="";
		}
	}
	for(ProjectTask after : project.getListOfTask())
	{
		if(CommonFuntion.checkContain(afterData,after.getTaskId()+""))
			{
			//thoi gain can thay doi cv tiep theo
			Long dateDiff = CommonFuntion.removeTime(new Date(data.getDueDate()))-CommonFuntion.removeTime(new Date(after.getStartDate()));
			updatePlanOfAfter( after,list,project.getListOfTask(),dateDiff);
			
			}
	}
	
}

void updatePlanOfAfter(ProjectTask root,List<ProjectTaskDTO> list,List<ProjectTask> listData,Long dateDiff)
{
	Boolean isLeaf = false;
for(ProjectTaskDTO taskDTO: list)
{
	if(root.getId().equals(taskDTO.getId()))
	{
		isLeaf=true;
		root.setStartDate(root.getStartDate()+dateDiff);
	}
}

if(!isLeaf)
{
	
	String afterData="";
	if(root.getDependent()!=null&&!root.getDependent().equals(""))
	{
		afterData = root.getDependent().substring(root.getDependent().indexOf("|"));
		
		if(afterData.length()>1)
		{
			afterData=afterData.substring(1);
		}
		else
		{
			afterData="";
		}
	}
	root.setStartDate(root.getStartDate()+dateDiff);
	root.setDueDate(root.getDueDate()+dateDiff);
	for(ProjectTask after : listData)
	{
		if(CommonFuntion.checkContain(afterData,after.getTaskId()+""))
			{
			
			Long dateDiff2 = CommonFuntion.removeTime(new Date(root.getDueDate()))-CommonFuntion.removeTime(new Date(after.getStartDate()));
			updatePlanOfAfter( after,list,listData,dateDiff2);
			
			}
	}
	
	}
}


	@Override
	public ProjectTaskDTO CreateTask(ProjectTaskDTO data,List<ProjectTaskDTO> listTask) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectTask task = null;
		try {
			// kiem tra xem la up date hay them moi
			if (data.getId() != null && data.getId() != "") {
				//neu la update lay du lieu cu de so sanh
				task = pm.getObjectById(ProjectTask.class, data.getId());
				// neu ban dau co cha
				if (task.getParentId() != data.getParentId()) {
					
					if (task.getParentId() != 0) {
						// xoa task id trong list subtask cua cha
						updateParentForDelete(task.toDTO(), listTask);
					}
					if(data.getParentId()!=0)
					{
					// them task id vao list subtask cua cha moi
					updateParentForAdd(data,listTask);
					}
				}
				else
				{
					//neu cha khong thay doi
					//kiem tra trong so co thay doi khong
					if(data.getWeight()!=task.getWeight())
					{
						
					    if(task.getParentId()!=0)
					    {
					    	ProjectTaskDTO parentTask = getFromList(task.getParentId(), listTask);
							Double oldWork = (task.getFinishedWork()/task.getAmountOfWork())*(task.getWeight()/100)*parentTask.getAmountOfWork();
						    Double newWork = (data.getFinishedWork()/data.getAmountOfWork())*(data.getWeight()/100)*parentTask.getAmountOfWork();
						    parentTask.setFinishedWork(parentTask.getFinishedWork()+newWork-oldWork);
						    
						    updateTask(parentTask);
						    updateAllMinestone(parentTask, listTask);
					    updateWorkOfParent(parentTask,newWork-oldWork,listTask);
					    }
					}
				}
				task.updateFromDTO(data);

			} else {
				// neu la them moi
				Project project = pm.getObjectById(Project.class, data
						.getProjectId());
				data.setTaskId(getLastTaskId() + 1);
				task = new ProjectTask(data);
				if (task.getSubTasks() == null) {
					task.setSubTasks("");
				}
				project.addTask(task);
				pm.makePersistent(project);
				// task moi add co cha update list subtask cua task cha
				if (task.getParentId() != 0) {
					updateParentForAdd(task.toDTO(), listTask);
					//updateParentForAdd(task.getParentId(), task.getTaskId());
				}
			}

		}

		finally {
			pm.close();
		}
		return task.toDTO();

	}

	@Override
	public void updateWorkOfParent(ProjectTaskDTO subTask ,Double work,List<ProjectTaskDTO> listTask)
	{
		ProjectTaskDTO task = getFromList(subTask.getParentId(), listTask);
		if(task!=null)
		{
			Double workOfParent = task.getAmountOfWork()*(work/subTask.getAmountOfWork())*subTask.getWeight()/100;
			task.setFinishedWork(task.getFinishedWork()+workOfParent);
			updateTask(task);
			updateAllMinestone( task, listTask);
			if(task.getParentId()!=0)
			{
				updateWorkOfParent(task,workOfParent,listTask);
				
			}
		}
	}
	

	//ham update cong viec milestone theo cong viec cua cha
	public void updateAllMinestone(ProjectTaskDTO task,List<ProjectTaskDTO> listTask)
	{
//		if(task.getSubTasks()!=null&&!task.getSubTasks().equalsIgnoreCase(""))
//		{
//			for(int i =0;i<listTask.size();i++)
//			{
//				if(task.getSubTasks().contains(listTask.get(i).getTaskId()+"")&&listTask.get(i).getIsMile()==1)
//				{
//					listTask.get(i).setFinishedWork(task.getFinishedWork());
//					updateTask(listTask.get(i));
//				}
//			}
//		}
	}
	
	
	String getAllAfterOftask(String after,List<ProjectTaskDTO> taskList)
	{   
		
		String newAfter = "";
		for(int i =0;i<taskList.size();i++)
		{   
			String afterData ="";
			
			if(taskList.get(i).getDependent()!=null&&!taskList.get(i).getDependent().equalsIgnoreCase(""))
			{
				
				 afterData = taskList.get(i).getDependent().substring(taskList.get(i).getDependent().indexOf("|"));
				if(afterData.length()>1)
				{
					afterData=afterData.substring(1);
				}
				else
				{
					afterData="";
				}
			}
			
			if(CommonFuntion.checkContain(after,taskList.get(i).getTaskId()+"")&&afterData!=null&&afterData.length()>0)
			{
				newAfter = newAfter+","+afterData;
			}
			
		}
		if(newAfter.length()>0)
		{
			//sub+=newSub;
			after += getAllAfterOftask(newAfter,taskList);
			
		}
		
		return after;
	}

	
	

	@Override
	public void updateTaskForClose(ProjectTaskDTO data,List<ProjectTaskDTO> listTask)
	{
		TaskConstrainServiceImpl constrainServer = new TaskConstrainServiceImpl();
		data = getFromList(data.getTaskId(), listTask);
	String afterData ="";	
		String preData="";
		if( data.getDependent()!=null&& data.getDependent().length()>1)
		{
			//cat lay pre
			 preData =  data.getDependent().substring(0, data.getDependent().indexOf("|"));
			afterData = data.getDependent().substring(data.getDependent().indexOf("|"));
			if(afterData.length()>1)
			{
				afterData=afterData.substring(1);
			}
			else
			{
				afterData="";
			}	
		}
		
		if(data.getStatus()==1&&data.getParentId()!=0)//
		{
			updateWorkOfParent(data, data.getFinishedWork()*-1, listTask);
		}
		
		if((data.getSubTasks()!=null&&!data.getSubTasks().equals(""))||!afterData.equals(""))
		{
			for(ProjectTaskDTO task:listTask)
			{
				if(CommonFuntion.checkContain(afterData,task.getTaskId()+""))
				{
					updateTaskForClose(task,listTask);
				}
				if(data.getSubTasks()!=null&&CommonFuntion.checkContain(data.getSubTasks(),task.getTaskId()+""))
				{
					updateTaskForClose(task,listTask);
				}
			}
		}
		if(!preData.equals(""))
		{
			//constrainServer.deleteAllConstrainOfTask(data,listTask);
		}

		data.setStatus(3);
		data.setFinishDate(CommonFuntion.removeTime(new Date()));
		updateForFinish(data);
	}
	
//	@Override
//	public void updateTaskForClose(ProjectTaskDTO data,List<ProjectTaskDTO> listTask)
//	{
//		String afterData ="";
//		String sub ="";
//		if(data.getSubTasks()!=null)
//		{
//			sub= getAllOfSub(sub, listTask) ;
//		}
//		
//		if( data.getDependent()!=null&& data.getDependent().equals(""))
//		{
//			afterData = data.getDependent().substring(data.getDependent().indexOf("|"));
//			if(afterData.length()>1)
//			{
//				afterData=afterData.substring(1);
//			}
//			else
//			{
//				afterData="";
//			}	
//		}
//		
//		
//		//neu  co task tiep theo thi close tat ca cac task tiep theo
//		if(!afterData.equals(""))
//		{
//			afterData=getAllAfterOftask( afterData,listTask);
//			for(ProjectTaskDTO task:listTask)
//			{
//				if(afterData.contains(task.getTaskId()+""))
//				{
//					task.setStatus(3);
//					updateTask(task);
//				}
//				if(sub.contains(task.getTaskId()+""))
//				{
//					task.setStatus(3);
//					updateTask(task);
//				}
//			}
//		}
//		//update task hien tai
//		data.setStatus(3);
//		updateTask(data);
//	}
//	
	@Override
	public void updateTask(ProjectTaskDTO data)
	{
		try
		{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			ProjectTask task = null;
			task = pm.getObjectById(ProjectTask.class, data.getId());
			task.updateFromDTO(data);
			pm.close();
		}catch(Exception ex)
		{
			System.out.println(ex.getMessage());
		}
		
	}
	
	public ProjectTaskDTO getFromList(int taskId, List<ProjectTaskDTO> listTask) {
		if (listTask != null && listTask.size() > 0) {
			for (int i = 0; i < listTask.size(); i++) {
				if (listTask.get(i).getTaskId() == taskId) {
					return listTask.get(i);
				}
			}
		}
		return null;

	}



	public void updateParentForDelete(ProjectTaskDTO subTask, List<ProjectTaskDTO> listTask) {

		try {
			
			ProjectTaskDTO parentTask = getFromList(subTask.getParentId(),
					listTask);
			//neu co task cha
			if (parentTask != null) {	
					// kiem tra task con co phai la con duy nhat ko
					String[] listOfSub = parentTask.getSubTasks().split(",");
					String newListOfSub = "";
					// duyet va cap nhap lai list task con cua task cha
					for (int i = 0; i < listOfSub.length; i++) {
						// neu task con co id khac task bi xoa thi cong id vao
						// list task con moi
						if (Integer.parseInt(listOfSub[i]) != subTask
								.getTaskId()) {
							if (newListOfSub.equalsIgnoreCase("")) {
								newListOfSub = listOfSub[i];
							} else {
								newListOfSub = newListOfSub + ","
										+ listOfSub[i];
							}
						}
					}
					// set list task con cua task cha = list task con moi lay
					// duoc
					parentTask.setSubTasks(newListOfSub);
					// neu task bi xoa la task con duy nhat cua task cha
					if (newListOfSub.equalsIgnoreCase("")) {
						// cap nhap lai nhom cua task cha
						parentTask.setGroup(0);
						//update task cha
						updateTask(parentTask);
					}
					else {
						updateTask(parentTask);
					}
			}
			
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}

	/* update lai list task con cua task cha khi them moi task con */
	public void updateParentForAdd(ProjectTaskDTO subTask, List<ProjectTaskDTO> listTask) {

		try {
			// List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();

			ProjectTaskDTO parentTask = getFromList(subTask.getParentId(),
					listTask);
			if (parentTask != null) {
				// kiem tra task cha da co con chua
				if (parentTask.getSubTasks().equalsIgnoreCase("")) {
                  
					// neu task cha chua co con set group task cha =1
					parentTask.setGroup(1);
					parentTask.setOptUserId("0");
					parentTask.setSubContructor("0");
					// them task con vao list sub cua task cha
					parentTask.setSubTasks("" + subTask.getTaskId());
					// update task cha
					updateTask(parentTask);
				} else {
				    	// them task con vao list sub cua task cha
						parentTask.setSubTasks(parentTask.getSubTasks() + ","
								+ subTask.getTaskId());
						updateTask(parentTask);
				}

			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}


	@SuppressWarnings("unchecked")
	@Override
	public List<ProjectTaskDTO> getListOfTask() {
		List<ProjectTaskDTO> projTaskList = new ArrayList<ProjectTaskDTO>();

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(ProjectTask.class);
		try {
			List<ProjectTask> list = (List<ProjectTask>) q.execute();
			for (ProjectTask projTask : list) {
				projTaskList.add(projTask.toDTO());

			}
		} catch (Exception e) {
			System.out.print(e.getMessage());
		} finally {
			pm.close();
		}
		return projTaskList;

	}

	@Override
	public ProjectTaskDTO getTaskById(String taskId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectTask TaskInfo;
		try {
			TaskInfo = pm.getObjectById(ProjectTask.class, taskId);
			
		} finally {
			pm.close();
		}

		return TaskInfo.toDTO();
	}
	@Override
	public void deleteListTask(List<ProjectTaskDTO> list,List<ProjectTaskDTO> listAll) {
		// TODO Auto-generated method stub

		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getParentId() != 0) {
					updateParentForDelete(list.get(i),listAll);
				}
				deleteSub(list.get(i).getTaskId(),listAll);
			}

		}

	}

	private void deleteSub(int taskId, List<ProjectTaskDTO> listAll) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			ProjectTaskDTO temp = getFromList(taskId, listAll);
			ProjectTask task =  pm.getObjectById(ProjectTask.class,temp.getId());
			if (task != null) {
				
				if (task.getGroup() == 1) {
					String[] listOfSub = task.getSubTasks().split(",");
					for (int i = 0; i < listOfSub.length; i++) {
						deleteSub(Integer.parseInt(listOfSub[i]), listAll);
					}
				}
				pm.deletePersistent(task);
		
			}
		}
		catch(Exception ex){
			System.out.print(ex.getMessage());
		}finally {
			pm.close();
		}
	}

	@Override
	public int getLastTaskId() {
		// TODO Auto-generated method stub
		try {

			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query q = pm.newQuery(ProjectTask.class);
			q.setResult(" max(taskId)");
			// unique=true implicitly since the query result includes
			// thus the returned Object[] is not wrapped by a Collection
			// Object[] result = (Object[]) q.execute ();
			Integer id = (Integer) q.execute();
			return id;
			// int i = result.length;
			// if(result != null &&result[0]!=null)
			// {
			// return Integer.parseInt(result[0].toString());
			// }
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return 0;
		}

	}

	@Override
	public ProjectTaskDTO getTaskByTaskId(int TaskId) {
		// TODO Auto-generated method stub
		List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String WhereString = "taskId ==" + TaskId;
		Query q;
		q = pm.newQuery(ProjectTask.class, WhereString);
		try {

			List<ProjectTask> list = (List<ProjectTask>) q.execute();

			for (ProjectTask task : list) {
				listTask.add(task.toDTO());
				break;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			pm.close();
		}

		if (listTask != null && listTask.size() > 0) {
			return listTask.get(0);
		} else {
			return null;
		}
	}


	
	@Override
	public List<TaskConstrainDTO> getListConstrain(String taskId) {
		// TODO Auto-generated method stub
		List<TaskConstrainDTO> list = new ArrayList<TaskConstrainDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectTask taskInfo;
		try {
			taskInfo = pm.getObjectById(ProjectTask.class, taskId);
			if (taskInfo.getListOfConstrain() != null) {
				for (int i = 0; i < taskInfo.getListOfConstrain().size(); i++)
					list.add(taskInfo.getListOfConstrain().get(i).toDTO());
			}

		} finally {
			pm.close();
		}
		return list;
	}



	@Override
	public List<ProjectTaskDTO> getTaskByUserID(String projectId, String userId) {
		List<ProjectTaskDTO> taskList = new ArrayList<ProjectTaskDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String WhereString = " projectId ==  \"" + projectId + "\""
				+ " && optUserId== \"" + userId + "\"";
		Query q = pm.newQuery(ProjectTask.class, WhereString);
		try {
			List<ProjectTask> list = (List<ProjectTask>) q.execute();
			for (ProjectTask task : list) {
				taskList.add(task.toDTO());
			}
		} catch (Exception e) {
			e.getMessage();
		} finally {
			pm.close();
		}
		return taskList;
	}

	@Override
	public void startWork(ProjectTaskDTO task)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
		task.setStatus(1);
		
	    updateTask(task);
		if(task.getParentId()!=0)
		{
			ProjectTaskDTO parentTask = getTaskByTaskId(task.getParentId());
			startWork(parentTask);
		}
		else
		{
			Project project = pm.getObjectById(Project.class,task.getProjectId());
			if(project.getStatus()==0)
			{
				project.setStatus(1);
				//can use
				//project.setStartDate(CommonFuntion.removeTime(new Date()));
				//project.setStartDate(CommonFuntion.removeTime(new Date(task.getStartDate())));
			}
		
		
			
		}
		}
		catch(Exception ex)
		{}
		finally
		{
			pm.close();
		}
		
	}

	public Double getWorkFromChild(ProjectTaskDTO data,Long date,List<ProjectTaskDTO> listTask)
	{
	
		if(data.getGroup()==0)
		{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query q = pm.newQuery(DailyReportDetail.class,"taskId==\""+data.getId()+"\" && createdOnDate<"+ date +" &&( status == 0||status == 1||status == 2)");
			q.setResult ("sum(workToFinished)");
			Double result = (Double) q.execute (); 
			if(result!=null)
			{
			return result;
			}
			else
			{
				return 0d;
			}
		}
		else
		{
			String sub="";
			if(data.getSubTasks()!=null&&!data.getSubTasks().equals(""))
			{
				sub = data.getSubTasks();
			}
			Double workOfParent=0d;
			for(ProjectTaskDTO task : listTask)
			{
				if(CommonFuntion.checkContain(sub,task.getTaskId()+""))
				{
					Double workFromChild = getWorkFromChild(task,date,listTask);
					workOfParent +=( workFromChild/task.getAmountOfWork())*task.getWeight()*data.getAmountOfWork()/100;
					
				}
			}
			return workOfParent;
			
		}
	}
	@Override
	public Double getTatolWorkAtDate(ProjectTaskDTO data,Long date)
	{
		Long time = CommonFuntion.removeTime(new Date(date));
		time = time+24*60*60*1000;
		List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();
		listTask = getListOrderTaskByProjectId(data.getProjectId());
		if(data.getGroup()==0)
		{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query q = pm.newQuery(DailyReportDetail.class,"taskId==\""+data.getId()+"\" && createdOnDate<"+ time+" &&( status == 0||status == 1||status == 2)");
			q.setResult ("sum(workToFinished)");
			Double result = (Double) q.execute (); 
			if(result!=null)
			{
			return result;
			}
			else
			{
				return 0d;
			}
		}
		else
		{
			String sub="";
			if(data.getSubTasks()!=null&&!data.getSubTasks().equals(""))
			{
				sub = data.getSubTasks();
			}
			Double workOfParent=0d;
			for(ProjectTaskDTO task : listTask)
			{
				if(CommonFuntion.checkContain(sub,task.getTaskId()+""))
				{
					Double workFromChild = getWorkFromChild(task,time,listTask);
					workOfParent +=( workFromChild/task.getAmountOfWork())*task.getWeight()*data.getAmountOfWork()/100;
					
				}
			}
			return workOfParent;
			
		}
		
	}
	@Override
	public List<ProjectTaskDTO> getListOrderTaskByProjectId(String projectId) {
		// TODO Auto-generated method stub
		List<ProjectTaskDTO>  result = new ArrayList<ProjectTaskDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(ProjectTask.class,"projectId==\""+projectId+"\"");
	//	q.setOrdering("startDate ascending, dueDate ascending ");
		q.setOrdering("startDate ascending");
		try {
			List<ProjectTask> list = (List<ProjectTask>) q.execute();
			for (ProjectTask projectTask : list) {
				result.add(projectTask.toDTO());
			}
		} catch (Exception e) {
			// logger.warning(e.getMessage());
		} finally {
			pm.close();
		}
		return result;
	}
	
//	@Override
//	public List<ProjectTaskDTO>  getListOrderTaskByProjectId(String projectId)
//	{
//		List<ProjectTaskDTO>  result = new ArrayList<ProjectTaskDTO>();
//		PersistenceManager pm = PMF.get().getPersistenceManager();
//		Query q = pm.newQuery(ProjectTask.class,"projectId==\""+projectId+"\"");
//		q.setOrdering("startDate ascending");
//		try {
//			List<ProjectTask> list = (List<ProjectTask>) q.execute();
//			for (ProjectTask projectTask : list) {
//				result.add(projectTask.toDTO());
//			}
//		} catch (Exception e) {
//			// logger.warning(e.getMessage());
//		} finally {
//			pm.close();
//		}
//		return result;
//	}
//	public void updateWotkOfParent(int parentId ,Double work)
//	{
//		ProjectTaskDTO task = getTaskByTaskId(parentId);
//		if(task!=null)
//		{
//			task.setFinishedWork(task.getFinishedWork()+work);
//			updateTask(task);
//			if(task.getParentId()!=0)
//			{
//				updateWorkOfParent(task.getParentId(),work);
//			}
//		}
//	}
}
